package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.AttachCategoryEnumWaybill;
import cn.huiyunche.base.service.enums.AttachTypeEnum;
import cn.huiyunche.base.service.enums.DWaybillDamageAuditEnum;
import cn.huiyunche.base.service.enums.WaybillIsDamageEnum;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.interfaces.DWaybillAttachService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.DWaybillAttachMapper;
import cn.huiyunche.base.service.mappers.DWaybillMapper;
import cn.huiyunche.base.service.model.DWaybill;
import cn.huiyunche.base.service.model.DWaybillAttach;
import cn.huiyunche.base.service.model.DWaybillAttachExample;
import cn.huiyunche.base.service.vo.DWaybillAttachVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.UserShowVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DWaybillAttachServiceImpl implements DWaybillAttachService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DWaybillAttachServiceImpl.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private DWaybillAttachMapper dWaybillAttachMapper = null;

    @Autowired
    private DWaybillMapper dWaybillMapper = null;

    private DWaybillMapper getDWaybillMapper() {
        return this.dWaybillMapper;
    }

    private DWaybillAttachMapper getDWaybillAttachMapper() {
        return this.dWaybillAttachMapper;
    }

    private UserService getUserService() {
        return this.userService;
    }

    @Override
    public Result<Object> modify(String waybillId, String picKeys) throws Exception {
        LOGGER.info("add params waybillId: {}, picKeys: {}", waybillId, picKeys);
        Result<Object> result = new Result<>(true, null, "添加成功");
        if (StringUtils.isBlank(waybillId)) {
            LOGGER.info("waybillId is not null");
            throw new BusinessException("运单ID不能为空");
        } else if (StringUtils.isBlank(picKeys)) {
            LOGGER.info("pic keys is not null");
            throw new BusinessException("图片不能为空");
        }
        // 删除当前运单带伤发运图片附件
        DWaybillAttachExample example = new DWaybillAttachExample();
        example.createCriteria().andWaybillIdEqualTo(Long.valueOf(waybillId))
                .andCategoryEqualTo(AttachCategoryEnumWaybill.INJURED.getValue());
        this.getDWaybillAttachMapper().deleteByExample(example);
        List<String> picLists = JSONArray.parseArray(picKeys, String.class);
        // 构建附件对象
        UserShowVo vo = this.getUserService().getCurrentUser();
        LOGGER.info("current user: {}", vo);
        for (String string : picLists) {
            DWaybillAttach dAttach = new DWaybillAttach();
            dAttach.setWaybillId(Long.valueOf(waybillId));
            dAttach.setUserId(vo.getId());
            dAttach.setUserName(vo.getRealName());
            dAttach.setCategory(AttachCategoryEnumWaybill.INJURED.getValue());
            dAttach.setType(AttachTypeEnum.INJURED_PHOTO.getValue());
            dAttach.setPicKey(string);
            this.getDWaybillAttachMapper().insertSelective(dAttach);
            result.setData(dAttach.getId());
        }
        DWaybill dWaybill = this.getDWaybillMapper().selectByPrimaryKey(Long.valueOf(waybillId));
        if (null != dWaybill) {
            dWaybill.setIsDamage(WaybillIsDamageEnum.T.getValue());
            dWaybill.setDamageAudit(DWaybillDamageAuditEnum.AUDITING.getValue());
            LOGGER.info("dWaybill isDamage: {}", dWaybill.getIsDamage());
            // 回写带伤发运状态、审核状态
            this.getDWaybillMapper().updateByPrimaryKeySelective(dWaybill);
        }
        return result;
    }

    @Override
    public Result<List<DWaybillAttachVo>> listPic(Long waybillId) throws Exception {
        LOGGER.info("listPic params waybillId: {}", waybillId);
        Result<List<DWaybillAttachVo>> result = new Result<>(true, null, "查询成功");
        if (waybillId == null || waybillId == 0) {
            LOGGER.info("waybillId is not null");
            throw new BusinessException("运单ID不能为空");
        }
        DWaybillAttachExample example = new DWaybillAttachExample();
        example.createCriteria().andWaybillIdEqualTo(waybillId)
                .andCategoryEqualTo(AttachCategoryEnumWaybill.INJURED.getValue());
        List<DWaybillAttach> lists = this.getDWaybillAttachMapper().selectByExample(example);
        List<DWaybillAttachVo> vos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(lists)) {
            lists.stream().filter((item) -> !item.getPicKey().equals("")).forEach(item -> {
                try {
                    DWaybillAttachVo vo = new DWaybillAttachVo();
                    PropertyUtils.copyProperties(vo, item);
                    vo.setPicURL(QiniuUtils.generateDownloadTicket(item.getPicKey(), ""));
                    vos.add(vo);
                } catch (Exception e) {
                    LOGGER.error("copyDWaybillAttachVo error: {}", e);
                    throw new BusinessException("复制VO异常");
                }
            });
        }
        result.setData(vos);
        return result;
    }

}
